package com.atguigu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.Excel.ExcelData;
import com.atguigu.eduservice.entity.subjectVo.SubjectNestedVo;
import com.atguigu.eduservice.entity.subjectVo.SubjectVo;
import com.atguigu.eduservice.listener.ExcelListener;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author lhl
 * @since 2022-07-01
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void addSubject(EduSubjectService eduSubjectService, MultipartFile file) {
        try{
            EasyExcel.read(file.getInputStream(), ExcelData.class,new ExcelListener(eduSubjectService)).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
        }
        // 直接调用easyExcel
    }

    @Override
    public List<SubjectNestedVo> getInfos() {
        QueryWrapper<EduSubject> SubjectyWrapper = new QueryWrapper<>();
        SubjectyWrapper.eq("parent_id","0");
        // 首先获取一级分类
        List<EduSubject> oneSubjects = this.list(SubjectyWrapper);
        // 获取二级分类
        QueryWrapper<EduSubject> SubjectyWrapper2 = new QueryWrapper<>();
        SubjectyWrapper2.ne("parent_id","0");
        List<EduSubject> twoSubjects = this.list(SubjectyWrapper2);
        ArrayList<SubjectNestedVo> resData = new ArrayList<>();
        // 包装对象
        for (EduSubject oneSubject : oneSubjects) {
            SubjectNestedVo subjectNestedVo = new SubjectNestedVo();

            // 使用spring中的工具类进行属性的填充
            BeanUtils.copyProperties(oneSubject,subjectNestedVo);
            resData.add(subjectNestedVo);
            // 填充二级分类
            ArrayList<SubjectVo> subjectVos = new ArrayList<>();
            for(EduSubject s : twoSubjects){
                if(s.getParentId().equals(oneSubject.getId())){
                    SubjectVo subjectVo = new SubjectVo();
                    BeanUtils.copyProperties(s,subjectVo);
                    subjectVos.add(subjectVo);
                }
            }
            subjectNestedVo.setChildren(subjectVos);
        }
        return resData;
    }

}
